import sys
import getopt

from updater._updater import OpenRPGUpdater

class CLIUpdater(OpenRPGUpdater):
    section = None
    def check_updates(self, force=False):
        super(CLIUpdater, self).check_updates()

        if force or (not self.update_done and self.is_update):
            self.section = self.c_section

            self.show_ui()

    def show_ui(self):
        packages = self.remote_packages.find(self.section).getiterator('package')
        versions = {}
        for pkg in packages:
            versions[pkg.get('version')] = pkg

        vk = versions.keys()
        vk.sort()
        vk.reverse()

        if self.section == self.c_section:
            print "Your current version is %s.%s" % (self.c_version,
                                                     self.c_revision)

        print "Current Section: %s\n" % self.section
        print "Note: To skip updater call start_server with -b or --noupdate options"

        i = 0
        options = []
        for version in vk:
            options.append(str(i))
            msg = str(i) + ") " + vk[i] + '.' + versions[vk[i]].get('revision')
            self.write(msg)
            i += 1

        options.append(str(i))
        msg = str(i) + ") Switch Sections"
        self.write(msg)
        self.write(" ")
        selection = int(self.prompt("Please select the version you wish to update to (0):", options, '0'))

        try:
            new_ver = vk[selection]
        except IndexError:
            self.change_section()
            return

        self.build_update_tree(self.section, new_ver)
        self.do_updates()

    def change_section(self):
        sections = []
        for sec in self.remote_packages.getroot().getchildren():
            sections.append(sec)

        print "Current Section: %s\n" % self.section

        i = 0
        options = []
        for s in sections:
            options.append(str(i))
            msg = str(i) + ") " + sections[i].tag
            self.write(msg)
            i += 1

        selection = int(self.prompt("Please select the section you wish to update to (0):", options, '0'))

        self.section = sections[selection].tag

        self.show_ui()

    def prompt(self, msg, choices=None, default='0'):
        while True:
            r = raw_input(msg + ' ')
            if not r:
                return default
            if not choices:
                return r
            if r.lower() in choices:
                return r.lower()
            else:
                self.write("unrecognized response\n")

    def write(self, msg):
        print(msg)

if __name__ == '__main__':
    force = False
    bypass = False

    (opts, args) = getopt.getopt(sys.argv[1:], "fbn:phml:m:d:", ["help","manual","noupdate","directory="] )
    for o, a in opts:
        if o in ('-f', '--force'):
            force = True
        if o in ('-b','--noupdate'):
            bypass = True
    if not bypass:
        updater = CLIUpdater()
        updater.check_updates(force)
